package gui;
import com.google.gdata.client.*;
import com.google.gdata.client.calendar.*;
import com.google.gdata.data.*;
import com.google.gdata.data.acl.*;
import com.google.gdata.data.calendar.*;
import com.google.gdata.data.extensions.*;
import com.google.gdata.util.*;

import controller.ModelOperator;

import java.net.*;
import java.sql.DatabaseMetaData;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.io.*;

import model.Event;
import model.EventRepeatDaily;
import model.EventRepeatMonthly;
import model.EventRepeatNone;
import model.EventRepeatYearly;

import sample.util.*;
import util.Utility;
public class SysGoogle {
	private CalendarService myService=null;
	private CalendarFeed resultFeed = null;
	private URL feedUrl = null;
	private URL postURL = null;
	private SimpleDateFormat sdf;
	private SimpleDateFormat stf;	
	private CalendarEventEntry myEvent=null;
	private CalendarEventEntry insertedEntry;
	private CalendarEventFeed myResultsFeed = null;
	private CalendarEventFeed myFeed=null;
	private ModelOperator mos;	


	public ModelOperator getMos() {
		return mos;
	}
	public SysGoogle() {
		sdf = new SimpleDateFormat("yyyy-MM-dd");
		stf = new SimpleDateFormat("yyyyMMdd");
		try {
			mos= new ModelOperator("config/db.config");
		} catch (FileNotFoundException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} catch (ClassNotFoundException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} catch (SQLException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		myService = new CalendarService("exampleCo-exampleApper");
	        try {
				myService.setUserCredentials("rtlcalendar@gmail.com", "hello123456");
			} catch (AuthenticationException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}        

			try {
				feedUrl = new URL("http://www.google.com/calendar/feeds/default/allcalendars/full");
			} catch (MalformedURLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			try {
				resultFeed = myService.getFeed(feedUrl, CalendarFeed.class);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (ServiceException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		public void InsertGoogle(Event ev)
		{
				if(ev.getRepeat().toSQLString().charAt(0)!='N'){
					try {
						InsertRepeatGoogle(ev);
					} catch (ParseException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					}
				}

		//Set the title and description		
			else 
			{
				try {
					postURL = new URL("http://www.google.com/calendar/feeds/rtlcalendar@gmail.com/private/full");
				} catch (MalformedURLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				myEvent = new CalendarEventEntry();
				//Set the title and description
				myEvent.setTitle(new PlainTextConstruct(ev.getContent()));
				myEvent.setContent(new PlainTextConstruct(ev.getContent()));
	
				myEvent.addLocation(LocationConvert(ev));
				myEvent.addTime(ConvertDate(ev));
				// POST the request and receive the response:
				try {
					insertedEntry = myService.insert(postURL, myEvent);
					System.out.println("insert scccessfully");
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (ServiceException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}		
			}

	    }
	    private void InsertRepeatGoogle(Event ev) throws ParseException {
			List<Date> dates = ev.getDates();
			for (Date date : dates) {
				Event single_event = new Event (-1,
						date, ev.getTime(), ev.getPlace(),
						ev.getContent(), new EventRepeatNone());
				InsertGoogle (single_event);
			}
		}
		private String DateConvert(Event ev) {
			// TODO Auto-generated method stub
	    	String result=sdf.format(ev.getDate())+"T"+ev.getTime().toString()+"+08:00";   	
			return result;
		}
		public void DeleteGoogle(Event ev) throws IOException, ServiceException
	    {
		//	URL feedUrl = new URL("https://www.google.com/calendar/feeds/default/owncalendars/full");
		//	CalendarFeed resultFeed = myService.getFeed(feedUrl, CalendarFeed.class);			
			URL feedUr = new URL("https://www.google.com/calendar/feeds/default/private/full");
			Query myQuery = new Query(feedUr);
			myQuery.setFullTextQuery(ev.getContent());
			CalendarEventFeed myResultsFeed1 = myService.query(myQuery,
			    CalendarEventFeed.class);				
			for(int i=0;i<myResultsFeed1.getEntries().size();i++) {
				  CalendarEventEntry firstMatchEntry = (CalendarEventEntry)
			      myResultsFeed1.getEntries().get(i);	
				  System.out.println(firstMatchEntry.getTitle().getPlainText()); 
				  firstMatchEntry.delete();	  
			}
			 System.out.println("delete success");
	    }
		public String TimeConvert(Event ev)
		{			
	    	String result=sdf.format(ev.getDate())+"T"+ev.getTime().toString();	    	
			return result;		
		}
		public Where LocationConvert(Event ev)
		{
			Where eventPlace=new Where();
			eventPlace.setValueString(ev.getPlace());
			return eventPlace;
			
		}
		public When ConvertDate(Event ev)
		{
			String stattime=DateConvert(ev);
			DateTime startTime = DateTime.parseDateTime(stattime);
			DateTime endTime = DateTime.parseDateTime(stattime);	
			When eventTimes = new When();
			eventTimes.setStartTime(startTime);
			eventTimes.setEndTime(endTime);
			return eventTimes;
		}
	    public void UpdataGoogle(Event nev,Event ev)
	    {
			URL feedUr = null;
			try {
				feedUr = new URL("https://www.google.com/calendar/feeds/default/private/full");
			} catch (MalformedURLException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			Query myQuery = new Query(feedUr);
			myQuery.setFullTextQuery(ev.getContent());
			CalendarEventFeed myResultsFeed1 = null;
			try {
				myResultsFeed1 = myService.query(myQuery,
				    CalendarEventFeed.class);
			} catch (IOException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			} catch (ServiceException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}		

			
			for(int i=0;i<myResultsFeed1.getEntries().size();i++) {
				  CalendarEventEntry firstMatchEntry = (CalendarEventEntry)
			      myResultsFeed1.getEntries().get(i);	
				  System.out.println(firstMatchEntry.getTitle().getPlainText()); 
				  firstMatchEntry.setTitle(new PlainTextConstruct(nev.getContent()));
				  firstMatchEntry.addLocation(LocationConvert(nev));
				  firstMatchEntry.addTime(ConvertDate(nev));	
				  try {
					firstMatchEntry.update();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (ServiceException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}				  
				  System.out.println("update success");
	  
			}
	    }
		public static void main(String[] args) throws IOException, ServiceException
		{
		}
	
}
